package com.atguigu.crowd.interceptor;

import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.exception.AccessForbiddenException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录状态拦截器
 * <p>
 * 1.配置拦截类
 * 2.将拦截类注册到拦截器里
 * <p>
 * *
 */
public class LoginStatusInterceptor extends HandlerInterceptorAdapter {

    Logger logger = LoggerFactory.getLogger(LoginStatusInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //如果session里能够取出用户信息，说明在登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("loginAdmin");

        //如果没登录抛未登录异常，这个异常跳转到异常页面
        if (admin == null) {
            throw new AccessForbiddenException("请登录后再操作");
        }

        //走到这放行
        return true;
    }
}
